using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.PL;
using Apps.Models.PL;
using Apps.IBLL.PL;

namespace Apps.BLL.PL
{
	public partial class PL_RL_DETAILSBLL: Virtual_PL_RL_DETAILSBLL,IPL_RL_DETAILSBLL
	{
        

	}
    public class Virtual_PL_RL_DETAILSBLL
    {
        [Dependency]
        public IPL_RL_DETAILSRepository m_Rep { get; set; }

        public virtual List<PL_RL_DETAILSModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<PL_RL_DETAILS> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.DETAIL_ID.Contains(queryStr)
                                || a.CREW_ID.Contains(queryStr)
                                || a.TEAM_ID.Contains(queryStr)
                                || a.BATCH_CODE.Contains(queryStr)

                                || a.CREATE_USER_ID.Contains(queryStr)

                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<PL_RL_DETAILSModel> GetPagerList(ref GridPager pager, Expression<Func<PL_RL_DETAILS, bool>> whereLambda)
        {

            var queryData = m_Rep.Context.PL_RL_DETAILS.Where(whereLambda.Compile());

            var queryData2 = from m in queryData
                             join um in m_Rep.Context.SysUser on m.CREATE_USER_ID equals um.Id into jd
                             from u in jd.DefaultIfEmpty()
                             select new PL_RL_DETAILSModel
                             {
                                 DETAIL_ID = m.DETAIL_ID,
                                 CREW_ID = m.CREW_ID,
                                 TEAM_ID = m.TEAM_ID,
                                 BATCH_CODE = m.BATCH_CODE,
                                 STATUS = m.STATUS,
                                 TEAMName=m.PUB_TEAM.TEAM_NAME,
                                 CREWName=m.PUB_CREW.CREW_NAME,
                                 CREATE_USER_ID = m.CREATE_USER_ID,
                                 CREATE_USER_NAME = u.TrueName,
                                 CREATE_TIME = m.CREATE_TIME,
                                 PLAN_DATE = m.PLAN_DATE
                             };
            pager.totalRows = queryData2.Count();
            //排序
            queryData2 = LinqHelper.SortingAndPaging(queryData2.AsQueryable(), pager.sort, pager.order, pager.page, pager.rows);
            return queryData2.ToList();
        }

        public virtual List<PL_RL_DETAILSModel> GetList(Expression<Func<PL_RL_DETAILS, bool>> whereLambda)
        {

            IQueryable<PL_RL_DETAILS> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<PL_RL_DETAILSModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<PL_RL_DETAILSModel>();
        }

        public virtual List<PL_RL_DETAILSModel> CreateModelList(ref IQueryable<PL_RL_DETAILS> queryData)
        {

            List<PL_RL_DETAILSModel> modelList = (from r in queryData
                                                  select new PL_RL_DETAILSModel
                                                  {
                                                      DETAIL_ID = r.DETAIL_ID,
                                                      CREW_ID = r.CREW_ID,
                                                      TEAM_ID = r.TEAM_ID,
                                                      BATCH_CODE = r.BATCH_CODE,
                                                      STATUS = r.STATUS,
                                                      CREATE_USER_ID = r.CREATE_USER_ID,
                                                      CREATE_TIME = r.CREATE_TIME,
                                                      PLAN_DATE = r.PLAN_DATE
                                                  }).ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, PL_RL_DETAILSModel model)
        {
            try
            {

                var entitys = m_Rep.GetList(m=>m.PLAN_DATE==model.PLAN_DATE&&m.CREW_ID==model.CREW_ID&&m.TEAM_ID==model.TEAM_ID);
                if (entitys.Count() > 0)
                {
                    errors.Add(Convert.ToDateTime(model.PLAN_DATE).ToString("yyyy-MM-dd")+"存在相同机组，相同班组的记录");
                    return false;
                }

                PL_RL_DETAILS entity = m_Rep.GetById(model.DETAIL_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new PL_RL_DETAILS();
                entity.DETAIL_ID = model.DETAIL_ID;
                entity.CREW_ID = model.CREW_ID;
                entity.TEAM_ID = model.TEAM_ID;
                entity.BATCH_CODE = model.BATCH_CODE;
                entity.STATUS = model.STATUS;
                entity.CREATE_USER_ID = model.CREATE_USER_ID;
                entity.CREATE_TIME = model.CREATE_TIME;
                entity.PLAN_DATE = model.PLAN_DATE;

                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<PL_RL_DETAILS, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.PL_RL_DETAILS.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                string DETAIL_ID = id.ToString();
                var mPL_RL_DETAILS = m_Rep.Context.PL_RL_DETAILS.Where(m => m.DETAIL_ID == DETAIL_ID).FirstOrDefault();
                m_Rep.Context.RL_SAMPLING.RemoveRange(mPL_RL_DETAILS.RL_SAMPLING);
                m_Rep.Context.PL_RL_DETAILS.Remove(mPL_RL_DETAILS);
                return m_Rep.Context.SaveChanges() > 0;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Edit(ref ValidationErrors errors, PL_RL_DETAILSModel model)
        {
            try
            {
                var entitys = m_Rep.Context.PL_RL_DETAILS.Where(m => m.PLAN_DATE == model.PLAN_DATE && m.CREW_ID == model.CREW_ID && m.TEAM_ID == model.TEAM_ID && m.DETAIL_ID != model.DETAIL_ID);
                if (entitys.Count() > 0)
                {
                    errors.Add(Convert.ToDateTime(model.PLAN_DATE).ToString("yyyy-MM-dd") + "存在相同机组，相同班组的记录");
                    return false;
                }

                PL_RL_DETAILS entity = m_Rep.Context.PL_RL_DETAILS.Where(m => m.DETAIL_ID == model.DETAIL_ID).FirstOrDefault();
             
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                if (entity.CREATE_USER_ID != model.CREATE_USER_ID)
                {
                    errors.Add("只能填报人修改");
                    return false;
                }

                if (entity.STATUS ==true)
                {
                    errors.Add("此入炉煤批次已生效，不能更改");
                    return false;
                }

                entity.CREW_ID = model.CREW_ID;
                entity.TEAM_ID = model.TEAM_ID;
                entity.BATCH_CODE = model.BATCH_CODE;
                entity.STATUS = model.STATUS;
                entity.PLAN_DATE = model.PLAN_DATE;

                if (m_Rep.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Enable(ref ValidationErrors errors, string DETAIL_ID,string UserID)
        {
            try
            {

                PL_RL_DETAILS entity = m_Rep.Context.PL_RL_DETAILS.Where(m => m.DETAIL_ID == DETAIL_ID).FirstOrDefault();

                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                if (entity.CREATE_USER_ID != UserID)
                {
                    errors.Add("只能填报人修改");
                    return false;
                }
                entity.STATUS = true;
                if (m_Rep.SaveChanges() > 0)
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual PL_RL_DETAILSModel GetById(object id)
        {
            if (IsExists(id))
            {
                PL_RL_DETAILS entity = m_Rep.GetById(id);
                PL_RL_DETAILSModel model = new PL_RL_DETAILSModel();
                model.DETAIL_ID = entity.DETAIL_ID;
                model.CREW_ID = entity.CREW_ID;
                model.TEAM_ID = entity.TEAM_ID;
                model.BATCH_CODE = entity.BATCH_CODE;
                model.STATUS = entity.STATUS;
                model.CREATE_USER_ID = entity.CREATE_USER_ID;
                model.CREATE_TIME = entity.CREATE_TIME;
                model.PLAN_DATE = entity.PLAN_DATE;
                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual PL_RL_DETAILSModel GetItem(Expression<Func<PL_RL_DETAILS, bool>> whereLambda)
        {

            PL_RL_DETAILS entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            PL_RL_DETAILSModel model = new PL_RL_DETAILSModel();
            model.DETAIL_ID = entity.DETAIL_ID;
            model.CREW_ID = entity.CREW_ID;
            model.TEAM_ID = entity.TEAM_ID;
            model.BATCH_CODE = entity.BATCH_CODE;
            model.STATUS = entity.STATUS;
            model.CREATE_USER_ID = entity.CREATE_USER_ID;
            model.CREATE_TIME = entity.CREATE_TIME;

            return model;
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<PL_RL_DETAILSModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.DETAIL_ID, "DETAIL_ID");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.CREW_ID, "CREW_ID");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.TEAM_ID, "TEAM_ID");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.BATCH_CODE, "BATCH_CODE");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.STATUS, "STATUS");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.CREATE_USER_ID, "CREATE_USER_ID");
            excelFile.AddMapping<PL_RL_DETAILSModel>(x => x.CREATE_TIME, "CREATE_TIME");

            //SheetName
            var excelContent = excelFile.Worksheet<PL_RL_DETAILSModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new PL_RL_DETAILSModel();
                entity.DETAIL_ID = row.DETAIL_ID;
                entity.CREW_ID = row.CREW_ID;
                entity.TEAM_ID = row.TEAM_ID;
                entity.BATCH_CODE = row.BATCH_CODE;
                entity.STATUS = row.STATUS;
                entity.CREATE_USER_ID = row.CREATE_USER_ID;
                entity.CREATE_TIME = row.CREATE_TIME;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<PL_RL_DETAILSModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        PL_RL_DETAILS entity = new PL_RL_DETAILS();
                        entity.DETAIL_ID = model.DETAIL_ID;
                        entity.CREW_ID = model.CREW_ID;
                        entity.TEAM_ID = model.TEAM_ID;
                        entity.BATCH_CODE = model.BATCH_CODE;
                        entity.STATUS = model.STATUS;
                        entity.CREATE_USER_ID = model.CREATE_USER_ID;
                        entity.CREATE_TIME = model.CREATE_TIME;

                        db.PL_RL_DETAILS.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }

        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }

        public virtual decimal GetBathCode(DateTime BathCodeDate)
        {
            string datetime = BathCodeDate.ToString("yyyy-MM-dd");
            return m_Rep.Context.Database.SqlQuery<Decimal>($"SELECT FUN_GET_BATCHCODE(to_date('{datetime}','yyyy-MM-dd')) FROM DUAL").FirstOrDefault();
        }
        public void Dispose()
        {

        }

    }
}
